package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.enums.AddressDefaultStatusEnum;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.model.dto.response.AddressBookPageQueryResDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.apache.tomcat.jni.Address;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private MapApi mapApi;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    /**
     * 新增用户地址
     * @param addressBookUpsertReqDTO 地址信息
     */

    @Override
    public void insertAddress(AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        //获取当前用户id，用来组合最后的数据
        Long userId = UserContext.currentUserId();
        //如果新增地址设置为默认，取消其他默认地址
        if(addressBookUpsertReqDTO.getIsDefault() == 1){
            cancelDefault(userId);
        }
        AddressBook addressBook = BeanUtils.copyBean(addressBookUpsertReqDTO, AddressBook.class);
        addressBook.setUserId(userId);

        //组装详细地址
        String completeaddress = addressBookUpsertReqDTO.getProvince()
                + addressBookUpsertReqDTO.getCity()
                + addressBookUpsertReqDTO.getCounty()
                + addressBookUpsertReqDTO.getAddress();

        //如果请求体中没有经纬度，需要调用第三方api根据详细地址获取经纬度
        if(ObjectUtils.isEmpty(addressBookUpsertReqDTO.getLocation())){
            //远程请求高德获取经纬度
            LocationResDTO locationByAddress = mapApi.getLocationByAddress(completeaddress);
            //经纬度（字符串格式：经度，纬度），经度在前，维度在后
            String location = locationByAddress.getLocation();
            addressBookUpsertReqDTO.setLocation(location);
        }
        if(StringUtils.isNotEmpty(addressBookUpsertReqDTO.getLocation())){
            //经度
            addressBook.setLon(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[0]));
            addressBook.setLat(NumberUtils.parseDouble(addressBookUpsertReqDTO.getLocation().split(",")[1]));

        }
        baseMapper.insert(addressBook);
    }

    /**
     * 分页查询地址
     * @param addressBookPageQueryReqDTO 地址请求信息
     * @return
     */
    @Override
    public PageResult<AddressBookPageQueryResDTO> page(AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        Page<AddressBook> page = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
        LambdaQueryWrapper<AddressBook> queryWrapper = Wrappers.<AddressBook>lambdaQuery().eq(AddressBook::getUserId, UserContext.currentUserId());
        Page<AddressBook> addressBookPage = baseMapper.selectPage(page, queryWrapper);
        return PageUtils.toPage(addressBookPage, AddressBookPageQueryResDTO.class);
    }

    /**
     * 根据地址查询id
     * @param id 主键id
     * @return
     */
    @Override
    public AddressBookPageQueryResDTO queryAddressById(Long id) {
        AddressBook addressBook = baseMapper.selectById(id);
        AddressBookPageQueryResDTO addressBookPageQueryResDTO = BeanUtils.copyBean(addressBook, AddressBookPageQueryResDTO.class);
        return addressBookPageQueryResDTO;
    }


    /**
     * 根据详细的id更改相关的信息
     * @param addressBookUpsertReqDTO 请求体
     */
    @Override
    public void upInsertAddressById(AddressBookUpsertReqDTO addressBookUpsertReqDTO, Long id) {
        if(addressBookUpsertReqDTO.getIsDefault() == AddressDefaultStatusEnum.ISDEFAULT.getStatus()){
            cancelDefault(UserContext.currentUserId());
        }

        LocationResDTO locationByAddress = mapApi.getLocationByAddress(addressBookUpsertReqDTO.getAddress());
        //经纬度（字符串格式：经度，纬度），经度在前，维度在后
        String location = locationByAddress.getLocation();
        Double Lon = null, Lat = null;
        if(StringUtils.isNotEmpty(location)){
            Lon = NumberUtils.parseDouble(location.split(",")[0]);
            Lat = NumberUtils.parseDouble(location.split(",")[1]);
        }

        lambdaUpdate().eq(AddressBook::getId, id)
                .eq(AddressBook::getUserId,UserContext.currentUserId())
                .set(AddressBook::getLon, Lon)
                .set(AddressBook::getLat, Lat)
                .set(AddressBook::getCity, addressBookUpsertReqDTO.getCity())
                .set(AddressBook::getCounty, addressBookUpsertReqDTO.getCounty())
                .set(AddressBook::getIsDefault, addressBookUpsertReqDTO.getIsDefault())
                .set(AddressBook::getName, addressBookUpsertReqDTO.getName())
                .set(AddressBook::getAddress, addressBookUpsertReqDTO.getAddress())
                .set(AddressBook::getProvince, addressBookUpsertReqDTO.getProvince())
                .set(AddressBook::getPhone, addressBookUpsertReqDTO.getPhone())
                .update();
    }

    /**
     * 取消默认
     * @param userId
     */
    private void cancelDefault(Long userId){
        lambdaUpdate().eq(AddressBook::getUserId, userId)
                .set(AddressBook::getIsDefault, AddressDefaultStatusEnum.NOTDEFAULT.getStatus())
                .update();
    }

}
